package Services.DBConn;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.logging.Level;
import java.util.logging.Logger;

public class DatabaseConnection {
    private String dbConnectionURL;
    private String dbName;
    private String dbUsername;
    private String dbPassword;
    
    protected ResultSet results;
    protected Connection conn;
    protected PreparedStatement pstmt;
    
    public DatabaseConnection(){
        this.dbConnectionURL = "jdbc:mysql://bookStore4280.db.7528882.hostedresource.com:3306/";
        this.dbName = "bookStore4280";
        this.dbUsername = "bookStore4280";
        this.dbPassword = "BScCM2014!";
        this.setup();
    }
    
    public void setup() {
        try {
        	System.out.println("Connecting to DB");
            Class.forName("com.mysql.jdbc.Driver").newInstance();
            this.conn = DriverManager.getConnection(this.dbConnectionURL+this.dbName+"?user="+this.dbUsername+"&password="+this.dbPassword);
        } catch (ClassNotFoundException ex) {
            Logger.getLogger(DatabaseConnection.class.getName()).log(Level.SEVERE, null, ex);
        } catch (SQLException ex) {
            Logger.getLogger(DatabaseConnection.class.getName()).log(Level.SEVERE, null, ex);
        } catch (InstantiationException e) {
			e.printStackTrace();
		} catch (IllegalAccessException e) {
			e.printStackTrace();
		}
    }
    
    public boolean execute(){
        this.results = null;
        
        try {
        	if(this.pstmt != null){
	        	boolean status = this.pstmt.execute();
	            if(status)
	                this.results = this.pstmt.getResultSet();
	
	            return status;
        	}
        } catch (SQLException ex) {
            Logger.getLogger(DatabaseConnection.class.getName()).log(Level.SEVERE, null, ex);
        }
        return false;
    }
    
    public void closeAll() {
        try {
        	System.out.println("Closing Connection to DB");
            if(this.conn != null)
                this.conn.close();

            if(this.pstmt != null)
                this.pstmt.close();
                
            if(this.getResults() != null)
                this.getResults().close();
        } catch (SQLException ex) {
            Logger.getLogger(DatabaseConnection.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    public ResultSet getResults() {
        return results;
    }
}